const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
const COLLECTION = 'account';

// 创建集合云函数入口函数
exports.main = async (event, context) => {
  const { userName } = event;
  const { pwd } = event;
  const query = {
    _id: userName,
  };
  if (pwd) {
    query.pwd = pwd;
  }
  try {
    const res = await db.collection(COLLECTION).where(query)
      .count();
    return res.total;
  } catch (err) {
    if (err.errCode == -502005) {
      // collection不存在，需要新建
      await db.createCollection(COLLECTION);
      // 这个自动添加几个账号
      for (let i = 1; i < 5; i++) {
        await db.collection(COLLECTION).add({
          data: {
            _id: `test${i}`,
            pwd: '123',
            cnt: 1,
          },
        });
      }
      return (await db.collection(COLLECTION).where(query)
        .count()).total;
    }
    console.log(err);
    return false;
  }
};
